package fr.resasante.ejb.util;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import fr.resasante.exception.SystemException;

/**
 * get a resource bundle with utf-8
 * 
 * @author GEFFROY-DE-VILLEBLAN
 * 
 */
public abstract class Utf8ResourceBundle {

	/**
	 * Resource Bundle that does the hard work
	 */
	private static class Utf8PropertyResourceBundle extends ResourceBundle {

		/**
		 * Bundle with unicode data
		 */
		private final PropertyResourceBundle bundle;

		/**
		 * Initializing constructor
		 * 
		 * @param bundle
		 */
		private Utf8PropertyResourceBundle(final PropertyResourceBundle bundle) {
			this.bundle = bundle;
		}

		@Override
		public Enumeration<String> getKeys() {
			return bundle.getKeys();
		}

		@Override
		protected Object handleGetObject(final String key) {
			final String value = bundle.getString(key);
			if (value == null) {
				return null;
			}
			try {
				return new String(value.getBytes("ISO-8859-1"), "UTF-8");
			} catch (final UnsupportedEncodingException e) {
				throw new SystemException("Encoding not supported", e);
			}
		}
	}

	/**
	 * Creates unicode friendly {@link PropertyResourceBundle} if possible.
	 * 
	 * @param bundle
	 *            the bundle
	 * @return Unicode friendly property resource bundle
	 */
	private static ResourceBundle createUtf8PropertyResourceBundle(final ResourceBundle bundle) {
		if (!(bundle instanceof PropertyResourceBundle)) {
			return bundle;
		}
		return new Utf8PropertyResourceBundle((PropertyResourceBundle) bundle);
	}

	/**
	 * Gets the unicode friendly resource bundle
	 * 
	 * @param baseName
	 *            the name of the properties file
	 * @param locale
	 *            the locale
	 * @see ResourceBundle#getBundle(String)
	 * @return Unicode friendly resource bundle
	 */
	public static final ResourceBundle getBundle(final String baseName, Locale locale) {
		return createUtf8PropertyResourceBundle(ResourceBundle.getBundle(baseName, locale));
	}
}
